package com.credithc.customers.manager.service.impl;

import com.credithc.baseserv.core.utils.UUIDUtils;
import com.credithc.baseserv.pageHelper.PageInfo;
import com.credithc.customers.base.codes.CustomerCodes;
import com.credithc.customers.base.constants.CustomerConstants;
import com.credithc.customers.base.exception.CustomerException;
import com.credithc.customers.base.mapper.CustomerImportMapper;
import com.credithc.customers.base.po.CustomerImportPo;
import com.credithc.customers.manager.asnycTask.AsyncTask;
import com.credithc.customers.manager.configure.FilePropertiesConfig;
import com.credithc.customers.manager.service.IFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.sql.Timestamp;
import java.util.Map;
import java.util.concurrent.Future;

/**
 * @author zhukai
 * @date 2018/12/20 9:51
 */
@Service
@Slf4j
public class FileServiceImpl implements IFileService {

    private final CustomerImportMapper customerImportMapper;

    private final AsyncTask asyncTask;

    private final FilePropertiesConfig filePropertiesConfig;

    @Autowired
    public FileServiceImpl(CustomerImportMapper customerImportMapper, AsyncTask asyncTask, FilePropertiesConfig filePropertiesConfig) {
        this.customerImportMapper = customerImportMapper;
        this.asyncTask = asyncTask;
        this.filePropertiesConfig = filePropertiesConfig;
    }

    @Override
    public void insertFile(String type, MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            log.info("========================================文件为空，停止上传");
            throw new CustomerException(CustomerCodes.BIZ_VALIDATE_ERROR,"上传文件为空");
        }
        String fileName = file.getOriginalFilename();
        if (!fileName.matches("^.+\\.(?i)(txt)$")) {
            log.info("========================================文件格式不正确，停止上传");
            throw new CustomerException(CustomerCodes.BIZ_VALIDATE_ERROR,"文件格式不正确");
        }

        String preName = fileName.substring(0, fileName.lastIndexOf("."));
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String path = filePropertiesConfig.getUploadPath();

        String retName = preName + "-upload" +suffixName;
        String uploadPath = path + retName;

        File newFile = new File(uploadPath);
        if(newFile.exists()){
            log.info("========================================存在相同名称文件，停止上传");
            throw new CustomerException(CustomerCodes.BIZ_VALIDATE_ERROR,"存在相同名称文件");
        }
        if (!newFile.getParentFile().exists()) {
            newFile.getParentFile().mkdirs();
        }
        file.transferTo(newFile);

        String importId = UUIDUtils.getUUID();
        CustomerImportPo importPo = new CustomerImportPo();
        importPo.setId(importId);
        importPo.setFileName(retName);

        Integer importType = CustomerConstants.IMPORT_TYPE_PRE;
        if ("personal".equals(type)) {
            importType = CustomerConstants.IMPORT_TYPE_PERSONAL;
        } else if ("company".equals(type)) {
            importType = CustomerConstants.IMPORT_TYPE_COMPANY;
        }
        importPo.setImportType(importType);
        importPo.setCreateTime(new Timestamp(System.currentTimeMillis()));
        importPo.setImportStatus(CustomerConstants.IMPORT_STATUS_ING);
        importPo.setFilePath(uploadPath);
        customerImportMapper.insert(importPo);
        Future<Boolean> a = asyncTask.uploadFile(uploadPath,importId,importType);
    }

    @Override
    public Map<String, PageInfo> queryUpload(int pageNo, int limit) {
        return null;
        /*Map<String, PageInfo> map = new HashMap<>(1);
        Page<CustomerImportPo> page = PageHelper.startPage(pageNo, limit);
        List<CustomerImportPo> pos = customerImportMapper.selectAll();
        List<CustomerImportVo> vos = new ArrayList<>();
        for (CustomerImportPo po : pos) {
            CustomerImportVo vo = new CustomerImportVo();
            BeanUtils.copyProperties(po, vo);
            vo.setCreateTime(CustomerUtils.timestamp2Stirng(po.getCreateTime()));
            vo.setFinishTime(CustomerUtils.timestamp2Stirng(po.getFinishTime()));
            vo.setImportStatus((po.getImportStatus() != null && po.getImportStatus().equals(CustomerConstants.STATUS_SUCCESS)) ? "导入完成" : "导入失败");
            vos.add(vo);
        }
        map.put("pageInfo", new PageInfo(vos, (int) page.getTotal(), pageNo, limit));
        return map;*/
    }

}
